package eu.ec.ellipcis.integration.ws.receiver;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.integration.Message;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.stereotype.Component;

import eu.ec.ellipcis.integration.ws.domain.jaxb.AccountBalanceRequest;

@Component
public class AccountMessageReceiver implements Runnable {

    final static int RECEIVE_TIMEOUT = 1000;

    protected QueueChannel channel;

    @Value("#{messageChannel}")
    public void setChannel(QueueChannel channel) {
        this.channel = channel;
    }

    public void handleAccountMessage() {
        Message<?> accountMessage;

        while (true) {
            accountMessage = channel.receive(RECEIVE_TIMEOUT);
            if (accountMessage != null) {
                handleAccount((AccountBalanceRequest) accountMessage.getPayload());
            } else {
                try {
                    /** Handle some other tasks **/

                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    void handleAccount(AccountBalanceRequest accountBalanceRequest) {
        System.out.println("Received account request - " + accountBalanceRequest.toString());
    }

    public void run() {
        handleAccountMessage();
    }
}
